package com.nuanshui.heatedloan.credit.utils.handy;


import com.nuanshui.framework.springContext.SpringContextUtil;
import com.nuanshui.framework.utils.HttpUtil;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.UUID;


/**
 * Created by wangxw on 2017/6/30.
 * 翰迪认证的入口类
 */
public class HandyAuthEntrance {

    private  static  final Logger logger= LoggerFactory.getLogger(HandyAuthEntrance.class);

    private String channelId;

    private String uri;

    private String publicKey;

    /***
     * 通过构造方法在zk去获取参数值
     */
    public HandyAuthEntrance(){
        channelId= SpringContextUtil.getBean("credit.handy.channelId");
        uri=SpringContextUtil.getBean("credit.handy.channelId");
        publicKey=SpringContextUtil.getBean("credit.handy.publicKey");
        if(channelId==null){
            channelId=channelIdDefault;
        }
        if(uri==null){
            uri=uriDefault;
        }
        if(publicKey==null){
            publicKey=publicKeyDefault;
        }
    }

    /***
     * 以后可能不用了，在zk中获取
     */
    public static final String channelIdDefault = "11009013";
    public static final String uriDefault = "https://58.246.136.11:1443/dataservice/service.ac";
    public static final String publicKeyDefault = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIO4Vv2RuiB1KcIa6NTn1ZCTtUZFnf29Fkj0DpioFbgUXn0PJeNI4c3cjqGg72s6l3+SYACMUsrI5ruwhO9rNiUCAwEAAQ==";


    /**
     * 入口
     * @throws Exception
     * @throws UnsupportedEncodingException
     */
    public  String checkRiskSystem(String xml) throws UnsupportedEncodingException, Exception {
        String mkey = UUID.randomUUID().toString();

        // 加密报文体格式：BASE64(商户号)| BASE64(RSA(报文加密密钥))| BASE64(3DES(报文原文))
        //对公钥进行加密处理
        String strKey = RSACoder.encryptByPublicKey(new String(mkey.getBytes(),
                "utf-8"), publicKey);
        //对传输数据进行加密处理
        String strxml = new String(Base64.encode(DesUtil.encrypt(
                xml.toString().getBytes("utf-8"), mkey.getBytes())));
        //对商户通道的id进行加密处理并对加密后的三个参数进行拼接字符串
        String returnXml = new String(Base64.encode(this.channelId.getBytes("utf-8"))) + "|"
                + strKey + "|" + strxml;
        logger.info("-------------------------------------传送的数据为------------------------"+returnXml);
        long start = System.currentTimeMillis();
        logger.info("-------------------------------------开始调用接口------------------------");
        String reutrnResult = HttpUtil.sendXmlDataByPost(uri, returnXml);
        long end = System.currentTimeMillis();
        logger.info("-------------------------------------调用接口结束，返回的数据为------------------------"+reutrnResult);
        logger.info("-------------------------------------调用接口的时间为------------------------"+(end-start));

        //对返回的结果进行处理
        String xmlArr[] = reutrnResult.split("\\|");
        //失败的处理，并输出失败的信息
        if (xmlArr[0].equals("0")) {
            logger.info("-------------------------调用接口失败，错误信息为"+new String(Base64.decode(xmlArr[2]),
                    "utf-8"));
        }
        //成功的处理，并返回结果
        else {
            byte[] b = DesUtil.decrypt(Base64.decode(xmlArr[1]),
                    mkey.getBytes());
            String tradeXml = new String(b, "utf-8");
            //System.out.println(new String(Base64.encode(Md5Utils.md5ToHexStr(tradeXml).getBytes("utf-8"))));// BASE64(MD5(报文))
            return tradeXml;
        }
        return null;
    }
//    public static String readRespMsg(String xml){
//        if(StringUtils.isEmpty(xml)){
//            return "未知";
//        }
//        try {
//            Element ele = DocumentHelper.parseText(xml).getRootElement();
//            return ele.elementText("respDesc");
//        } catch (DocumentException e) {
//            return "未知2";
//        }
//
//
//    }
}
